import os.path
import shutil
import datetime
from globelly import *
from Class_PackagesWeb import *
from log import write_log


def __get_info_in_url(url):  # 通过URL提取 大版本，小版本，库，CPU架构四个信息  返回值：含有这四个信息的列表
    mod_debug_info = 0
    if mod_debug_info:
        url = "https://update.cs2c.com.cn/NS/V10/V10SP1/os/adv/lic/base/x86_64/Packages/"

    info = []
    info.append(url.split('/')[4])
    info.append(url.split('/')[5])
    info.append(url.split('/')[-4])
    info.append(url.split('/')[-3])

    if mod_debug_info:
        print("",
        "大版本:   {}\n".format(info[0]),
        "小版本：  {}\n".format(info[1]),
        "库：     {}\n".format(info[2]),
        "CPU架构：{}".format(info[3]))

    return info

def __get_date(): # 获取今天日期  eg：2022-11-11
    result=datetime.date.today()
    date = str(result)
    # print(date,type(date))
    return date

def create_dir_by_queue(queue): # 根据web队列，在WorkDir/databases下生成对应的文件夹
    mod_debug_info = 0
    for url in queue:
        info = __get_info_in_url(url)
        dirpath = WorkDir + 'databases/{}/{}/{}/{}/'.format(__get_date(), info[0], info[1], info[2])
        if not os.path.exists(dirpath):
            os.makedirs(dirpath)


def download_webdata(queue):
    web_queue_url = queue
    for mumber in web_queue_url:
        packsinfo = __get_info_in_url(mumber)
        filepath = WorkDir + 'databases/{}/{}/{}/{}/{}'.format(__get_date(), packsinfo[0], packsinfo[1], packsinfo[2], packsinfo[3])
        if not os.path.exists(filepath):

            packweb = PackagesWeb(mumber)
            packslist = packweb.get_rpm_list()
            __record_data(filepath, packslist)
            write_log('download',"版本：{}  小版本号：{}  库：{}  架构：{} ---- 数据下载完毕".format(packsinfo[0],packsinfo[1],packsinfo[2],packsinfo[3]))
        else:
            write_log('download',"版本：{}  小版本号：{}  库：{}  架构：{} ---- 数据已存在  ".format(packsinfo[0],packsinfo[1],packsinfo[2],packsinfo[3]))

def __record_data(path, info):    # 数据记录模块
    with open(path,'a',encoding='UTF-8') as f:
        for name in info:
            f.write(name + '\n')
